package com.wgz.mp.generator.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * @author wgz
 * @title
 * @Package PACKAGE_NAME
 * @data 2021/4/1 19:44
 */
public class WebConfig implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        // servletContext 上下文对象
        // 容器
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        // 注册 spring 类配置
        ctx.register(SpringMvcConfig.class);
        // 注入 setServletContext
        ctx.setServletContext(servletContext);
        // 核心控制器
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        // 路径拦截
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        // 过滤器
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic characterEncodingFilter1 = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);

        characterEncodingFilter1.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,DispatcherType.INCLUDE, DispatcherType.ASYNC),true,"/*");
        //监听器
//        servletContext.addListener();
    }
}
